<?php
namespace Nawa;
/**
 * Nawa Customized Customer.
 *
 * @author Xavier VILAIN
 * @package \Nawa\Customer
 * @license
 */
use Fox\Common\Customer\Type;
use Nawa\MedicalStudy\Role;
use Fox\Utilities\Dates;
use Fox\Utilities\Format;
use Fox\Dao;
use Fox\Dao\SqlFragment;

class Customer extends \Fox\Common\Customer
{
	/**
	 * Link to medical studies
	 */
	const LINK_MEDICAL_STUDIES = "medicalStudies";

	/**
	 * Link to medical studies
	 */
	const LINK_MEDICAL_STUDIES_PARTNERS = "medicalStudiesPartners";

	/**
	 * Link to medical studies
	 */
	const LINK_MEDICAL_CENTERS = "medicalCenters";

	/**
	 * Link to medical studies
	 */
	const LINK_MEDICAL_CENTER_MONITORINGS = "medicalCenterMonitorings";
	
	/**
	 * Document Grouping
	 */
	const DOC_CATEGORY_EMPLOYEE = "IN";

	/**
	 * Document Grouping
	 */
	const DOC_RESUME = "cv";

	/**
	 *
	 * User Object
	 * @var User
	 */
	private $user = null;

	/**
	 *
	 * Master Profile
	 * @var int
	 */
	private $proid = null;

	/**
	 * (non-PHPdoc)
	 * @see Fox\Common.Customer::afterSetFields()
	 */
	protected function afterSetFields(array $fields)
	{
		parent::afterSetFields($fields);
		if($this->applicationaccess == 1 && $this->canHaveAccess())
		{
			if(isset($fields['email1']))
			{
				$role = \Fox\Dao::load(Role::className(),$fields['function'].":".\Xview::instance()->language());
				$this->proid = $role->proid;
				$fields['proid'] = $role->proid;
				$fields['email'] = $fields['email1'];
				$this->user()->setFields($fields);
			}
		}
	}

	/**
	 *
	 * Check if the customer can have access to the application
	 */
	public function canHaveAccess()
	{
		if($this->type == self::TYPE_EMPLOYEE || $this->type == self::TYPE_BASIC)
		{
			return true;
		}
		return false;
	}

	/**
	 *
	 * Find all customer medical studies
	 * @return array
	 */
	public function medicalStudies($fragments = null)
	{
		$fragments[] = new SqlFragment("customerid = ? ",array($this->customerid));
		$finder = new MedicalStudy();
		$res = $finder->find(SqlFragment::combine($fragments),
		array("label" => false));
		return $res;
	}

	/**
	 * Count the number of open medical studies
	 * @return int
	 */
	public function medicalStudiesCount()
	{
		$infos = Dao::infos(MedicalStudy::className());
		$query = $infos->handle()->createQueryBuilder();
		$query->select('COUNT(*) AS nb')
		->from($infos->tableName(),'t');
		$fragment = new SqlFragment("customerid = ? AND status = ? ",
		array($this->customerid,MedicalStudy::STATUS_OPEN));
		return $fragment->pushIn($query)->execute()->fetchColumn();
	}

	/**
	 * After Create if the type is employee the system will automatically
	 * add an application user.
	 *
	 */
	protected function afterVersionCreate(\Fox\Version $version)
	{
		parent::afterVersionCreate($version);
		if($this->applicationaccess == 1 && $this->canHaveAccess())
		{
			$this->user()->create();
			$this->user()->updateWebApps(\Xview::instance()->id(),$this->proid);
			$this->user()->setPrefs('customercode',$this->getId());
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see Fox\Common.Customer::afterVersionUpdate()
	 */
	protected function afterVersionUpdate()
	{
		parent::afterVersionUpdate();
		if($this->isChangeType(self::CHANGE_DEFAULT)) {
			if($this->applicationaccess == 1)
			{
				if($this->user()->exists())
				{
					$this->user()->update();
				}
				else
				{
					$this->user()->create();
				}
				$this->user()->setPrefs(\User::PREFERENCE_LINK_TO_CONTACT,$this->getId());
				if(!empty($this->proid))
				{
					$this->user()->updateWebApps(\Xview::instance()->id(),$this->proid);
				}
			}
		}
	}

	/**
	 * Find corresponding access user if there is one
	 * @return User
	 */
	public function user()
	{
		if(empty($this->user))
		{
			$finder = new \User();
			$res = $finder->find(new SqlFragment("prfnm = ? AND prfvl = ?",
			array(\User::PREFERENCE_LINK_TO_CONTACT,
			$this->getId())),
			null,
			array(\User::$JOIN_PREFERENCES));
			if(count($res) == 1)
			{
				$this->user = $res[0];
			}
			else
			{
				$this->user = $finder;
				$this->user->dpara = Format::MASK_FRENCH;
				$this->user->npara = Dates::MASK_EURO;
				$this->user->activ = $this->applicationaccess;
				$this->user->fname = $this->name1;
				$this->user->email = $this->address()->email1;
			}
		}
		return $this->user;
	}

	/**
	 * Role / Authorization Profile
	 */
	public function role()
	{
		return $this->function;
	}

	/**
	 *
	 */
	public function email1()
	{
		return $this->address()->email1;
	}

	/**
	 * Load the lastest contact resume
	 * @return \Fox\Document
	 */
	public function resume()
	{
		$finder = new \Fox\Document();
		$res = $finder->find(new SqlFragment('customerid = ? and doctype = ?',
		array($this->getId(),self::DOC_RESUME)),
		array('udate' => 'DESC'),
		array(self::$JOIN_DOCUMENTS),
		1
		);
		if(count($res) > 0)
		{
			return $res[0];
		}
		return null;
	}

	/**
	 * Find Employees - Short Cut
	 * @return array
	 */
	public static function employees($fragments = null)
	{
		$object = self::className();
		$fragments[] = new SqlFragment("type = ?",array(self::TYPE_EMPLOYEE));
		$finder = new $object();
		return $finder->find(SqlFragment::combine($fragments),
		array('name1' =>false));
	}

	/**
	 * Find Employees - Short Cut
	 * @return array
	 */
	public static function customers($fragments = null)
	{
		$object = self::className();
		$fragments[] = new SqlFragment("type = ?",array(self::TYPE_BASIC));
		$finder = new $object();
		return $finder->find(SqlFragment::combine($fragments),
		array('name1' =>false));
	}
	
	public static function fullName($id) {
		try {
			$customer = \Fox\Dao::load(self::className(),$id);
			return $customer->name1;
		} catch(\Fox\Object\Exception\NotExist $e) {
			return $id;
		}
	}
}
// Link to Medical Centers Customer
\Fox\Object\Links::add(\Fox\Dao::link(MedicalStudy\MedicalCenter\Partner::className(),
MedicalStudy\MedicalCenter\Partner::LINK_CUSTOMER)
->to(Customer::className(), Customer::LINK_MEDICAL_CENTERS)
->on('customerid')
);
// Link to Customer
\Fox\Object\Links::add(\Fox\Dao::link(MedicalStudy\Partner::className(), MedicalStudy\Partner::LINK_CUSTOMER)
->to(Customer::className(),Customer::LINK_MEDICAL_STUDIES_PARTNERS)
->on('customerid')
);